package com.surveycomp.servlets;

import java.io.IOException;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.surverycomp.models.Challenge;
import com.surverycomp.models.Event;
import com.surverycomp.models.User;
import com.surveycomp.datastore.PMF;

public class FaceChallengeServlet extends BaseServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 4034007952798979586L;
	protected PersistenceManager pm = PMF.get().getPersistenceManager();

	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp) {
		try {

			// Fetch session - create one if one doesnt exist
			HttpSession s = req.getSession(true);
			User user;

			// redirect to a 'createUser' page
			if (s.getAttribute("userKey") == null) {
				resp.sendRedirect("createuser.jsp");
				return;
			} else {
				// Try to fetch userKey
				Key userKey = (Key) s.getAttribute("userKey");
				user = pm.getObjectById(User.class, userKey);
			}

			// Get event from request
			String eventId = req.getParameter("eventKey");
			Key eventKey = KeyFactory.createKey(Event.class.getSimpleName(),
					Long.parseLong(eventId));

			Event e = pm.getObjectById(Event.class, eventKey);

			s.setAttribute("eventKey", e.getKey());

			Long challengeKey = Long
					.parseLong(req.getParameter("challengeKey"));

			Challenge nextChallenge = pm.getObjectById(Challenge.class,
					KeyFactory.createKey(Challenge.class.getSimpleName(),
							challengeKey));

			boolean challengeAlreadyFaced = false;
			List<Key> challengesFaced = user.getFacedChallenges();

			// check if the challenge have already been faced by user
			challengeAlreadyFaced = challengesFaced.contains(nextChallenge
					.getKey());

			// Set boolean showing if the challenge has already been faced once!
			s.setAttribute("challengeFaced", challengeAlreadyFaced);
			// Set session scoped attribute 'challenge' as the next challenge.
			s.setAttribute("challenge", nextChallenge);
			s.setAttribute("user", user);

			resp.sendRedirect("facechallenge.jsp");

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException {
		try {
			HttpSession session = request.getSession();
			Challenge facedChallenge = (Challenge) session
					.getAttribute("challenge");
			User thisUser = (User) session.getAttribute("user");

			// Add the newly faced challenge to the list of faced challenges
			thisUser.addChallengeFaced(facedChallenge);

			String chosenAnswer = request.getParameter("possibleAnswers");

			boolean correctAnswer = facedChallenge.getAnswer().equals(
					chosenAnswer);
			if (correctAnswer) {
				thisUser.setScore(thisUser.getScore() + 1);
			}
			pm.makePersistent(thisUser);
			session.setAttribute("correctAnswer", correctAnswer);

			response.sendRedirect("responseRegistered.jsp");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	private Challenge getChallengeNotFaced(List<Challenge> challengesFaced,
			List<Challenge> allChallenges) {
		Challenge nextChallenge = null;

		// Get challenge to face
		for (Challenge aChallenge : allChallenges) {
			if (challengesFaced.size() == 0) {
				// If no challenges have been faced - get the first challenge in
				// the list
				// Of event challenges
				nextChallenge = allChallenges.get(0);
				break;
			} // Else - get the next challenge to face
			for (Challenge facedChallenge : challengesFaced) {
				if (!facedChallenge.getKey().equals(aChallenge.getKey())) {
					nextChallenge = aChallenge;
				}
			}
		}
		return nextChallenge;
	}**/
}
